<?php

namespace app\common\model;

use think\Model;

/**
 * 会员vip订单模型
 * Class VipOrderModel
 * @package app\common\model
 */
class VipOrderModel extends Model
{
    protected $name = 'vip_order';

    /**
     * 关联vip
     * @return \think\model\relation\HasOne
     */
    public function vip()
    {
        return $this->hasOne(VipModel::class, 'id', 'vid')
            ->field(['id', 'name']);
    }

    /**
     * 获取列表
     * @param $params
     * @param int $rows
     * @param int $page
     * @param string $fields
     * @return array
     * @throws \think\exception\DbException
     */
    public function getLists($params, $rows = 20, $page = 1, $fields = '*')
    {
        // 条件搜索
        if (!empty($params['where'])) {
            $this->where($params['where']);
        } else {
            if (!empty($params['keyword'])) {
                switch ($params['type']) {
                    case 1 :
                        $this->where(['a.order_no' => ['LIKE', '%' . $params['keyword'] . '%']]);
                        break;
                    case 2 :
                        $this->where(['b.nickname' => ['LIKE', '%' . $params['keyword'] . '%']]);
                        break;
                    case 3 :
                        $this->where(['b.mobile' => ['LIKE', '%' . $params['keyword'] . '%']]);
                        break;
                }
            }
            if (!empty($params['status'])) {
                $this->where('a.status', '=', $params['status']);
            }
            if (!empty($params['vid'])) {
                $this->where('a.vid', '=', $params['vid']);
            }
            if (!empty($params['user_id'])) {
                $this->where('a.user_id', '=', $params['user_id']);
            }
            // 时间范围查询
            if (!empty($params['start_time'])) {
                $this->where('a.create_time', '>=', $params['start_time']);
            }
            if (!empty($params['end_time'])) {
                $this->where('a.create_time', '<=', $params['end_time']);
            }
        }

        // 排序
        $order  = !empty($params['order']) ? $params['order'] : 'id DESC';
        $result = $this
            ->with(['vip'])
            ->alias('a')
            ->join('user b', 'a.user_id = b.id')
            ->field($fields)
            ->order($order)
            ->paginate($rows, false, [
                'page' => $page
            ]);

        $arr = [
            'list'      => [],
            'total'     => 0,
            'page'      => 1,
            'pageSize'  => $rows,
            'totalSize' => 0
        ];
        // 格式化数据信息
        if (!$result->isEmpty()) {
            $arr = [
                'list'      => $result->items(),
                'total'     => $result->total(),
                'page'      => $result->currentPage(),
                'pageSize'  => $result->listRows(),
                'totalSize' => $result->lastPage()
            ];
        }

        return $arr;
    }

    /**
     * 获取用户vip名称
     * @param $userId
     * @return mixed|string
     */
    public function getUserVipName($userId)
    {
        $name = '普通用户';
        $time = time();
        $vid  = $this
            ->where("user_id = {$userId} AND status = 1 AND expires_time > $time")
            ->value('vid');

        if (empty($vid)) {
            return $name;
        }

        $name = VipModel::where(['id' => $vid])->value('name');
        return $name;
    }

    /**
     * 添加
     * @param $data
     * @return bool|int|string
     */
    public function add($data)
    {
        if (empty($data) || !is_array($data)) {
            $this->error = '参数不正确';
            return false;
        }

        return $this->transaction(function () use ($data) {
            $vip                  = VipModel::where(['id' => $data['vid']])->find();
            $data['order_no']     = $this->getOrderNo();
            $data['pay_price']    = bcmul($vip->price, $data['num'], 2);
            $data['status']       = 1;
            $data['aid']          = 1;
            $data['pay_time']     = time();
            $data['create_time']  = time();
            $data['expires_time'] = $this->calculateVipNum($data['vid'], $data['num']);
            $id                   = $this->insertGetId($data);

            return $id;
        });
    }

    /**
     * 获取订单号
     * @return string
     */
    public function getOrderNo()
    {
        $orderNo = 'vip' . mt_rand(1, 9) . getRandomString(11, '0123456789');

        if ($this->where(['order_no' => $orderNo])->value('id')) {
            $this->getOrderNo();
        }

        return $orderNo;
    }

    /**
     * 计算到期时长
     * @param $vid
     * @param $num
     * @return false|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function calculateVipNum($vid, $num)
    {
        $vip         = VipModel::where(['id' => $vid])->find();
        $time        = time();
        $expiresTime = 0;
        // 计算时长
        switch ($vip['type']) {
            case 1 :
                // 按月
                $expiresTime = strtotime("+{$num} month", $time);
                break;
            case 2 :
                // 按季度
                $num         *= 3;
                $expiresTime = strtotime("+{$num} month", $time);
                break;
            case 3 :
                // 按年
                $expiresTime = strtotime("+{$num} year", $time);
                break;
        }

        return $expiresTime;
    }

    /**
     * 获取某条记录
     * @param $where
     * @return array|bool|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getItem($where, $fields = '*')
    {
        if (empty($where)) {
            $this->error = '参数不正确。';
            return false;
        }
        if (floor($where) > 0) {
            $where = ['id' => $where];
        }

        return $this->where($where)->field($fields)->find();
    }

    /**
     * 编辑
     * @param $data
     * @return bool
     */
    public function edit($data)
    {
        if (empty($data) || !is_array($data)) {
            $this->error = '参数不正确';
            return false;
        }

        if ($this->update($data)) {
            return true;
        } else {
            $this->error = '编辑出错了，请重新尝试。';
            return false;
        }
    }

    // 删除
    public function del($id)
    {
        if (empty($id)) {
            $this->error = '参数不正确';
            return false;
        }

        return $this->transaction(function () use ($id) {
            return $this->where(['id' => $id])->delete();
        });
    }
}